package com.hmall.trade.listener;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.hmall.api.client.item.ItemClient;
import com.hmall.api.client.payorder.PayorderClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.api.dto.PayOrderDto;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Slf4j
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final ItemClient itemClient;
    private final PayorderClient payorderClient;

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true", type = ExchangeTypes.DIRECT),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void orderDelayListener(Long orderid) {
        // 1.根据订单id查询order表
        log.info("订单延迟消息监听，订单id：{}", orderid);
        Order order = orderService.getById(orderid);
        // 2.检测订单状态，判断是否0未支付
        if (order == null || order.getStatus() != 1) {
            // 订单不存在或者不是“未支付”状态 已经处理过的，就直接结束（幂等性校验）
            return;
        }
        // 3.todo订单状态是未支付，需要查询支付单状态payorder表  支付单的biz_order_no 与交易单order  id 相同
        Long orderId = order.getId();
        PayOrderDto payOrderDto = payorderClient.queryPayOrderById(orderId);
        log.info("支付单信息：{}", payOrderDto);
        Integer payorderStatus = payOrderDto.getStatus();
        // 支付单状态不为 未支付状态（1） 才继续；
        if (payorderStatus != 1) {
            return;
        }

        //查询交易单付款状态
        if (order.getStatus() == 1) {
            //取消订单  将order表的status设置为5  //将payorder表status设置为2
            payorderClient.markPayOrderSuccess(orderId);

            boolean updateOrder = orderService.lambdaUpdate()
                    .eq(Order::getId, orderId)
                    .set(Order::getStatus, 5)
                    .set(Order::getCloseTime, LocalDateTime.now())
                    .update();

            log.info("取消订单结果：{}", updateOrder, "订单状态已修改为：" + order.getStatus());

            //回滚库存
            //  根据orderId 远程调用item的根据id查询订单详情发方法 ----查询订单详情，获取需要回滚的商品及数量

            List<OrderDetailDTO> items = new ArrayList<>();
            List<OrderDetail> itemdto = orderDetailService.queryIdNumsByorderId(orderId);
            for (OrderDetail itemDTO : itemdto) {
                Long itemId = itemDTO.getItemId(); // 购买商品id
                Integer num = itemDTO.getNum(); // 购买商品数量
                OrderDetailDTO dto = new OrderDetailDTO();
                dto.setItemId(itemId);
                dto.setNum(num);
                items.add(dto);
            }

            //回滚库存
            itemClient.SaveIdStack(items);


        } else if (order.getStatus() == 2){
            //如果已付款，标记交易状态为“已支付待发货”
            orderService.markOrderPaySuccess(orderid);
        }
    }
}

